package pv.map;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.google.android.gms.maps.model.LatLng;
import com.google.android.maps.GeoPoint;




public class EncodingPolylineAlgorithm extends GetPolylineAlgorithm {
	protected List<GeoPoint> decodePoly(String encoded) {

		List<GeoPoint> poly = new ArrayList<GeoPoint>();
		int index = 0, len = encoded.length();
		int lat = 0, lng = 0;

		while (index < len) {
			int b, shift = 0, result = 0;
			do {
				b = encoded.charAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);
			int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
			lat += dlat;

			shift = 0;
			result = 0;
			do {
				b = encoded.charAt(index++) - 63;
				result |= (b & 0x1f) << shift;
				shift += 5;
			} while (b >= 0x20);
			int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
			lng += dlng;

			GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
					(int) (((double) lng / 1E5) * 1E6));
			poly.add(p);
		}

		return poly;
	}

	@Override
	public RouteInfo encoding(JSONArray jsonArrayRoute) throws JSONException {
		// TODO Auto-generated method stub

		RouteInfo result;

		JSONObject polynejson = jsonArrayRoute.getJSONObject(0).getJSONObject(
				"overview_polyline");

		String distance = jsonArrayRoute.getJSONObject(0).getJSONArray("legs")
				.getJSONObject(0).getJSONObject("distance").getString("text");
		String duration = jsonArrayRoute.getJSONObject(0).getJSONArray("legs")
				.getJSONObject(0).getJSONObject("duration").getString("text");
		List<GeoPoint> polylines = decodePoly(polynejson.getString("points"));

		result = new RouteInfo(distance, duration,
				convertGeoPointToLatlng(polylines));

		return result;
	}

	private List<LatLng> convertGeoPointToLatlng(List<GeoPoint> polylines) {
		List<LatLng> result = new ArrayList<LatLng>();
		for (int i = 0; i < polylines.size(); i++) {
			result.add(new LatLng((polylines.get(i).getLatitudeE6() / 1E6),
					(polylines.get(i).getLongitudeE6() / 1E6)));
		}
		return result;

	}
}
